package com.alongstudio.account.commons.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

import javax.persistence.Id;


public class AnnotationUtil
{

	public static String getPkName(Class c)
	{
		Field fd[] = c.getDeclaredFields();
		for (int i = 0; i < fd.length; i++)
		{
			Annotation at[] = fd[i].getAnnotations();
			for (int j = 0; j < at.length; j++)
			{
				if (at[j] instanceof Id)
					return fd[i].getName();
			}
		}
		return null;
	}

	public static Object getPkValue(Object o)
	{
		Class c = o.getClass();
		Field fd[] = c.getDeclaredFields();
		for (int i = 0; i < fd.length; i++)
		{
			Annotation at[] = fd[i].getAnnotations();
			for (int j = 0; j < at.length; j++)
			{
				if (at[j] instanceof Id)
					try
					{
						return BeanUtil.getProperty(o, fd[i].getName());
					}
					catch (Exception e)
					{
						return null;
					}
			}
		}
		return null;
	}

	public static Class getPkType(Class c)
	{
		Field fd[] = c.getDeclaredFields();
		for (int i = 0; i < fd.length; i++)
		{
			Annotation at[] = fd[i].getAnnotations();
			for (int j = 0; j < at.length; j++)
			{
				if (at[j] instanceof Id)
					return fd[i].getType();
			}
		}
		return null;
	}

	public static java.io.Serializable getPkObject(Class c, String v)
	{
		c = AnnotationUtil.getPkType(c);
		try
		{
			Constructor cc = c.getConstructor(new Class[]
			{ v.getClass() });
			Object o = cc.newInstance(new Object[]
			{ v });
			return (java.io.Serializable) o;
		}
		catch (Exception ex)
		{
			return null;
		}
	}

}
